define(["../common"], function() {
	
	var pwdFormCfg = {
		fields: {
			pwd: "密码:required"
		}	
	};
	var bindFormCfg = {
		fields: {
			"#question_1": "问题1:required",
			"#question_2": "问题2:required",
			"#question_3": "问题3:required",
			"#answer_1": "答案1:required",
			"#answer_2": "答案2:required",
			"#answer_3": "答案3:required"
		}
	};
	
	// 防止自动填充
	$("input,select").val("");
	
	requirePlugin(["validator"],function() {
		$("#step_0").validator(pwdFormCfg);
		$("#step_1").validator(bindFormCfg);
	});
	
	// 获取绑定进度信息
	$.getJSON(g_userDomain + "/securityQuestion/isPwdVerified/json?r" + Math.random(), function(data) {
		
		// 显示表单
		if (!data.result) {
			$("#step_0").show();
			$(".step:eq(0)").addClass("active");
			$("#pwd").val("").focus();
		} else {
			$("#step_1").show();
			$(".step:lt(2)").addClass("active");		
		}
		
	});
	
	// 加载预置问题
	$.get(g_userDomain + "/securityQuestion/preset/json", function(data) {
		var list = data.split(";");
		var optionStr = '<option value="">-选择-</option>';
		for (var i in list) {
			optionStr += '<option value="' + list[i] + '">'+ list[i] + '</option>';
		}
		optionStr += '<option value="-1">自定义</option>';
		$("[id^=que_sel_]").append(optionStr);
	})
	
	// 事件：选择问题
	$("[id^=que_sel_]").change(function() {
		$this = $(this);
		if (parseInt($this.val()) === -1) {
			$this.next().removeClass("hidden");
			$this.next().val("").focus();
		} else {
			$this.next().addClass("hidden");
			$this.next().val($this.val());
		}
		// 清空答案
		var key = ($this.attr("id").split("_"))[2];
		$("#answer_" + key).val("");
	});
	
	// 密码
	$("#step_0").on('valid.form', function(e, form){
		var $form = $(form);
		if (!$form.lock()) return;
		
		$form.loadMsg("正在验证...");
		$.post(g_userDomain + "/securityQuestion/verifyPwdDo/json", $form.serialize(), function(data) {
			if (data.status !== 0) {
				$form.failMsg(data.message);
				 return;
			}
			$form.hideMsg();
			
			$("[id^=step_]").hide();
			$("#step_1").show();
			$(".step:eq(1)").addClass("active");
		});
		
	});
	
	// 绑定
	$("#step_1").on('valid.form', function(e, form){
		var $form = $(form);
		if (!$form.lock()) return;
		
		$form.loadMsg("正在保存...");
		$.post(g_userDomain + "/securityQuestion/do/json", $form.serialize(), function(data){
			if (data.status !== 0) {
				$form.failMsg(data.message);
				return;
			}
			$form.infoMsg("保存成功");
			
			$("[id^=step_]").hide();
			$("#step_2").show();
			$(".step:eq(2)").addClass("active");
		});
	});
	
});